package com.ny.controller;
import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.service.UserService;
import com.ny.until.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private final Map<String, Object> map = new HashMap<>();
    @RequestMapping("/selectUser")
    public Result selectUser(){
        return Result.success(userService.findAll());
    }
    @PostMapping("/login")
    public Result login(String username,String password){
        User user = userService.findUser(username,password);
        if (user != null) {
            String token = jwtUtil.generateToken(user.getUsername());// 生成Token
            jwtUtil.storeToken(token, user.getUsername());//存储打redis
            map.put("token", token);// token存储到map中、
            map.put("users", user);// 用户信息也存储在map中
            return Result.success(map);// 把数据传输到界面（前端）
        } else {
            return Result.error ("用户名和密码错误");//
        }
    }
    //注册
    @PostMapping("/register")
    public Result register( @RequestBody User user){
        if(userService.register(user)){
            return Result.success("注册成功");
        }
        else {
            return Result.error("用户已存在");
        }
    }
//    查询邮箱号是否存在:http://localhost:8081/findUserByEmail?email=<EMAIL>
    @PostMapping("/findUserByEmail")
    public Result findUserByEmail(String email){
        if(userService.findUserByEmail(email)>0){
            return Result.success("邮箱号已存在");
        }
        return Result.success("邮箱号不存在");
    }
//    给邮箱发送验证码：http://localhost:8081/sendEmail?email=<EMAIL>
    @PostMapping("/sendEmail")
    public Result sendEmail(String email){
        if(userService.findUserByEmail(email)<=0){
            return Result.error("邮箱号不存在");
        }
        userService.sendEmail(email);
        return Result.success("发送成功");
    }
//  http://localhost:8081/updateUser?email=<EMAIL>&code=123456&newPassword=123456
@PostMapping("/updateUser")
public Result updateUser(@RequestParam String email,@RequestParam String code, @RequestParam String newPassword){
    //判断验证码是否正确
    if(userService.findEmail(email,code)){
//         进行修改密码
       if (userService.updateUser(email,newPassword)>0){
           return Result.success("修改成功");
       }
       return Result.error("修改失败");
    }
    else {
        return Result.error("验证码不正确");
    }
}
//    1.输入QQ邮箱号  2.获取验证码 3.输入验证码 4.输入新密码 5.点击修改（发送）
//    1.输入邮箱获取到验证码，需要把验证码存储到redis   2.输入邮箱号以及验证码、密码  需要判断验证码是否正确。
}
